<template>
  <div>
    <x-card v-if="hasPerm('parent_page')">
      <div
        slot="content"
        class="table-page-search-wrapper"
      >
        <a-form layout="inline">
          <a-row :gutter="20">
            <a-col
              :md="6"
              :sm="24"
            >
              <a-form-item label="名称">
                <a-input
                  v-model="queryParam.Name"
                  allow-clear
                  placeholder="请输入家长或学生名称"
                />
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="24"
            >
              <a-form-item label="手机">
                <a-input
                  v-model="queryParam.PhoneNumber"
                  allow-clear
                  placeholder="请输入手机"
                />
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="24"
            >
              <a-form-item label="班级">
                <a-select
                  allowClear
                  v-model="queryParam.ClassId"
                  placeholder="请选择班级"
                >
                  <a-select-option
                    v-for="item in classList"
                    :key="item.id"
                    :value="item.id"
                  >{{
                    item.name
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col
              :md="2"
              :sm="24"
            >
              <a-button
                type="primary"
                @click="$refs.table.refresh(true)"
              >查询</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </x-card>
    <a-card :bordered="false">
      <s-table
        ref="table"
        :columns="columns"
        :data="loadData"
        :rowKey="record => record.id"
        :alert="options.alert"
        :rowSelection="options.rowSelection"
      >
        <template
          slot="operator"
          v-if="hasPerm('children:add')"
        >
          <a-button
            @click="wechatOperate(true)"
            icon="plus"
            type="primary"
          >开启微信端</a-button>
          <a-button
            @click="wechatOperate(false)"
            icon="minus"
            type="primary"
          >关闭微信端</a-button>
          <a-button @click="tongbushuju" icon="plus" type="primary" >同步数据</a-button>
          <a-button @click="exportNoAvatar" icon="download" type="primary" >导出无头像数据</a-button>
          <x-down
            style="display:none"
            ref="batchExport"
            @batchExport="batchExport"
          />
        </template>
        <span
          slot="action"
          slot-scope="text, record"
        >
          <a
            v-if="hasPerm('parent:edit')"
            @click="$refs.editForm.edit(record)"
          >编辑</a>
          <a-divider
            type="vertical"
            v-if="hasPerm('parent:edit') & hasPerm('parent:openorclosewechat')"
          />
          <a-popconfirm
            placement="topRight"
            title="关闭后，改成员不能使用微信端程序！"
            @confirm="() => weixinshezhi(record)"
          >
            <a v-if="hasPerm('parent:openorclosewechat') && record.isOpenWechat">关闭微信端</a>
          </a-popconfirm>
          <a
            v-if="hasPerm('parent:openorclosewechat') && !record.isOpenWechat"
            @click="weixinshezhi(record)"
          >开启微信端</a>
          <a-divider
            type="vertical"
            v-if="hasPerm('parent:reset') & hasPerm('parent:openorclosewechat')"
          />
          <a-popconfirm
            placement="topRight"
            title="重置后的密码为123456"
            @confirm="() => chongzhimima(record)"
          >
            <a v-if="hasPerm('parent:reset')">重置密码</a>
          </a-popconfirm>
          <a-divider
            type="vertical"
            v-if="hasPerm('parent:reset') & hasPerm('parent:delete')"
          />
          <a-popconfirm
            placement="topRight"
            title="确定要删除？"
            @confirm="() => shanchujiazhang([{ id: record.id }])"
          >
            <a v-if="hasPerm('parent:delete')">删除</a>
          </a-popconfirm>
        </span>
      </s-table>
      <add-form
        ref="addForm"
        :classList="classList"
        @ok="handleOk"
      />
      <edit-form
        ref="editForm"
        :classList="classList"
        @ok="handleOk"
      />
    </a-card>
      <device-list ref="deviceList"></device-list>
  </div>
</template>

<script>
import { STable, XCard, XDown } from '@/components'
import { sysPosList } from '@/api/modular/garden/classManage'
import { parentPage, parentDelete, openOrCloseWeChat, resetpassword, batchOpenOrCloseWeChat,ExportChildren } from '@/api/modular/parent/parentManage'
import addForm from './addForm'
import editForm from './editForm'
import deviceList from '../children/archives/deviceList.vue'

export default {
  components: {
    XDown,
    XCard,
    STable,
    addForm,
    editForm,
    deviceList
  },

  data() {
    return {
      // 查询参数
      queryParam: {},
      // 表头
      columns: [
        {
          title: '家长姓名',
          dataIndex: 'name'
        },
        {
          title: '幼儿姓名',
          dataIndex: 'childrensName'
        },
        {
          title: '与幼儿关系',
          dataIndex: 'childrensNameAndRelationship'
        },
        {
          title: '手机',
          dataIndex: 'phoneNumber'
        },
        {
          title: '工作单位',
          dataIndex: 'workplace'
        },
        {
          title: '学历',
          dataIndex: 'degreeStr'
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return parentPage(Object.assign(parameter, this.queryParam)).then(res => {
          return res.data
        })
      },
      selectedRowKeys: [],
      selectedRows: [],
      options: {
        alert: {
          show: true,
          clear: () => {
            this.selectedRowKeys = []
          }
        },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      classList: [],
      exportLoading:false
    }
  },

  created() {
    if (this.hasPerm('parent:edit')) {
      this.columns.push({
        title: '操作',
        width: '260px',
        dataIndex: 'action',
        scopedSlots: { customRender: 'action' }
      })
    }
    this.getClass()
  },
  methods: {
    wechatOperate(isOpen){
      if(!this.selectedRowKeys.length){
        this.$message.error('请选择家长')
        return
      }
      batchOpenOrCloseWeChat({
        ids: this.selectedRowKeys,
        isOpenWechat: isOpen
      }).then(res => {
        if(res.success){
            this.$refs.table.clearRefreshSelected()
        }
      })
    },
    tongbushuju(){
      this.$refs.deviceList.add(this.selectedRows, 3)
    },
    getClass() {
      let obj = {
        isArchived: false
      }
      sysPosList(obj).then(res => {
        this.classList = res.data
      })
    },

    /**
     * 单个删除
     */
    singleDelete(record) {
      const param = [{ id: record.id }]
      this.parentDelete(param)
    },
    /**
     * 批量删除
     */
    batchDelete() {
      const paramIds = this.selectedRowKeys.map(d => {
        return { id: d }
      })
      this.shanchujiazhang(paramIds)
    },
    /**
     * 删除
     */
    shanchujiazhang(param) {
      parentDelete(param)
        .then(res => {
          if (res.success) {
            this.$message.success('删除成功')
            this.$refs.table.clearRefreshSelected()
          } else {
            this.$message.error('删除失败：' + res.message)
          }
        })
        .catch(err => {
          this.$message.error('删除错误：' + err.message)
        })
    },
    weixinshezhi(record) {
      console.log(record)
      let paramas = { phoneNumber: record.phoneNumber }
      openOrCloseWeChat(paramas)
        .then(res => {
          console.log(res)
          if (res.success) {
            this.$message.success(res.message)
            this.$refs.table.clearRefreshSelected()
          } else {
            this.$message.error('操作失败：' + res.message)
          }
        })
        .catch(err => {
          this.$message.error('操作错误：' + err.message)
        })
    },
    chongzhimima(record) {
      let paramas = { id: record.id }
      resetpassword(paramas)
        .then(res => {
          console.log(res)
          if (res.success) {
            this.$message.success(res.message)
            this.$refs.table.clearRefreshSelected()
          } else {
            this.$message.error('操作失败：' + res.message)
          }
        })
        .catch(err => {
          this.$message.error('操作错误：' + err.message)
        })
    },
    /**
     * 批量导出
     */
    batchExport() {
      const paramIds = this.selectedRowKeys.map(d => {
        return { id: d }
      })
      sysPosExport(paramIds).then(res => {
        this.$refs.batchExport.downloadfile(res)
      })
    },
    handleOk() {
      this.$refs.table.refresh()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    liban(record) {
      let postData = {
        id: record.id
      }
      childrenLeaveClass(postData).then(res => {
        if (res.code === 200) {
          this.$refs.table.clearRefreshSelected()
          this.$message.success('离班成功')
        } else {
          this.$message.error('离班失败：' + res.message)
        }
      })
    },
    // 导出无头像家长数据
    exportNoAvatar(){
      this.exportLoading=true
      ExportChildren().then(res=>{
        this.$refs.batchExport.downloadfile(res)
      }).finally(()=>{
        this.exportLoading=false
      })
    }
  }
}
</script>

<style lang="less">
.table-operator {
  margin-bottom: 18px;
}
button {
  margin-right: 8px;
}
</style>
